<template>
  <a-range-picker
    class="j-range-date-picker"
    :disabled="disabled || readOnly"
    :placeholder="placeholder"
    @change="handleDateChange"
    :value="momVal"
    :showTime="showTime"
    :format="dateFormat"
    :getCalendarContainer="getCalendarContainer"
    v-bind="$attrs"/>
</template>
<script>
  import moment from 'moment'
  export default {
    name: 'JRangeDate',
    props: {
      placeholder:{
        type: Array,
        default: () => ['开始日期', '结束日期'],
        required: false
      },
      value:{
        type: Array,
        required: false,
        default: () => []
      },
      dateFormat:{
        type: String,
        default: 'YYYY-MM-DD',
        required: false
      },
      readOnly:{
        type: Boolean,
        required: false,
        default: false
      },
      disabled:{
        type: Boolean,
        required: false,
        default: false
      },
      showTime:{
        type: Boolean,
        required: false,
        default: false
      },
      getCalendarContainer: {
        type: Function,
        default: (node) => {
          // 查找最近的modal-body作为挂载点，如果没有则使用父节点
          // 注意：这里返回document.body可以解决大多数情况下的显示问题
          return document.body
        }
      }
    },
    data () {
      return {
        momVal: this.transformMoment(this.value)
      }
    },
    watch: {
      value (val) {
        this.momVal = this.transformMoment(val)
      }
    },
    methods: {
      moment,
      // 将字符串数组转换为moment对象数组
      transformMoment(dateStrArr) {
        if (!dateStrArr || dateStrArr.length !== 2) {
          return null
        }
        const [startDate, endDate] = dateStrArr
        if (!startDate || !endDate) {
          return null
        }
        return [
          moment(startDate, this.dateFormat),
          moment(endDate, this.dateFormat)
        ]
      },
      // 处理日期变更事件
      handleDateChange(dates, dateStrings) {
        this.$emit('change', dateStrings);
      }
    },
    // 指定父组件调用时的传值属性和事件类型
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style>
/* 确保日期选择器下拉框在模态框内正确显示 */
.j-range-date-picker {
  width: 100%;
}
.j-range-date-picker.ant-calendar-picker {
  z-index: 1050 !important;
}
</style> 